package org.liaohailong.victorlibrary.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import org.jetbrains.annotations.Nullable;
import org.liaohailong.library.widget.shopping.decoration.ShoppingItemDecoration;
import org.liaohailong.victorlibrary.R;
import org.liaohailong.victorlibrary.VictorApplication;
import org.liaohailong.victorlibrary.base.BaseActivity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Random;

/**
 * Author: Victor
 * E-mail: liaohailong190@foxmail.com
 * Date: 2019/6/22 9:36
 * Description: 电商平台界面
 */
public class ShoppingActivity extends BaseActivity implements View.OnClickListener {
    public static void show(Context context) {
        Intent intent = new Intent(context, ShoppingActivity.class);
        context.startActivity(intent);
    }


    private Adapter adapter = new Adapter();
    private ShoppingItemDecoration itemDecoration = new ShoppingItemDecoration(
            30,
            30,
            30,
            15,
            15,
            9,
            9
    );

    private RecyclerView.OnItemTouchListener onItemTouchListener = new RecyclerView.OnItemTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
            return false;
        }

        @Override
        public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {

        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }
    };

    private RecyclerView.OnChildAttachStateChangeListener onChildAttachStateChangeListener = new RecyclerView.OnChildAttachStateChangeListener() {
        @Override
        public void onChildViewAttachedToWindow(@NonNull View view) {

        }

        @Override
        public void onChildViewDetachedFromWindow(@NonNull View view) {

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping);

        RecyclerView listView = findViewById(R.id.recycler_view);
        listView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        listView.setItemAnimator(null);
        listView.addItemDecoration(itemDecoration);
        listView.addOnItemTouchListener(onItemTouchListener);
        listView.addOnChildAttachStateChangeListener(onChildAttachStateChangeListener);
        listView.setItemViewCacheSize(20);
        listView.setAdapter(adapter);

        /*
         * 多种类型布局共存
         * 或者
         * 每个ItemView中带有position相关信息显示时
         *
         * 从中间插入时，不能使用notifyItemInserted
         * 从中间删除时，不能使用notifyItemRemoved
         *
         * 否则会出现布局闪动的问题，这是
         * StaggeredGridLayoutManager内部布局逻辑引起的，不好优化。
         *
         * 所以只能使用notifyDataSetChanged()函数
         *
         * PS:仅从尾部追加或者从尾部删除可可以使用
         * notifyItemInserted(getItemCount());
         * or
         * notifyItemRemoved(getItemCount());
         * 这样不会出现布局闪动
         *
         * 总结：
         * 可以理解为当多种布局同时存在时，
         * 如果修改了中间的部分，那么必定需要重新计算后续的排放位置
         * 还有布局类型是否因为位置而改变。因此出现闪动实属正常。
         *
         * */

        findViewById(R.id.add_btn).setOnClickListener(this);
        findViewById(R.id.delete_btn).setOnClickListener(this);
        findViewById(R.id.add_middle_btn).setOnClickListener(this);
        findViewById(R.id.delete_middle_btn).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_btn:
                adapter.addOne();
                break;
            case R.id.delete_btn:
                adapter.removeOne();
                break;
            case R.id.add_middle_btn:
                adapter.addToMiddle();
                break;
            case R.id.delete_middle_btn:
                adapter.removeFromMiddle();
                break;
            default:
                break;
        }
    }

    private final class Adapter extends RecyclerView.Adapter<ShoppingViewHolder> {
        private int[] linearLayoutColors = {Color.parseColor("#FF00FF"), Color.parseColor("#80FF00FF")};
        private int[] gridLayoutColors = {Color.parseColor("#00FF00"), Color.parseColor("#8000FF00")};
        private int[] staggeredGridLayoutColors = {Color.parseColor("#FFFF00"), Color.parseColor("#80FFFF00")};

        private LinkedList<String> data = new LinkedList<>();

        private void addOne() {
            data.addLast(makeItemData());
//            notifyItemInserted(getItemCount());
            notifyDataSetChanged();
        }

        private void removeOne() {
            String itemData = data.pollLast();
            if (itemData != null) {
//                notifyItemRemoved(getItemCount());
                notifyDataSetChanged();
            }
        }

        private void addToMiddle() {
            int position = new Random().nextInt(data.size());
            data.add(position, makeItemData());
//            notifyItemInserted(position);
            notifyDataSetChanged();
        }

        private void removeFromMiddle() {
            int position = new Random().nextInt(data.size());
            String itemData = data.remove(position);
            if (itemData != null) {
//                notifyItemRemoved(position);
                notifyDataSetChanged();
            }
        }

        private String makeItemData() {
            return "Hello World : " + new SimpleDateFormat("hh:mm:ss", Locale.CHINA).format(new Date());
        }

        @NonNull
        @Override
        public ShoppingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int type) {
            ViewType itemViewType = ViewType.LINEAR_LAYOUT;
            for (ViewType viewType : ViewType.values()) {
                if (viewType.type == type) {
                    itemViewType = viewType;
                    break;
                }
            }

            TextView textView = new TextView(parent.getContext());
            textView.setGravity(Gravity.CENTER);
            StaggeredGridLayoutManager.LayoutParams layoutParams =
                    new StaggeredGridLayoutManager.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, itemViewType.height);
            if (itemViewType == ViewType.LINEAR_LAYOUT) {
                layoutParams.setFullSpan(true);
            } else {
                layoutParams.setFullSpan(false);
            }
            textView.setLayoutParams(layoutParams);
            return new ShoppingViewHolder(textView);
        }

        @Override
        public void onBindViewHolder(@NonNull ShoppingViewHolder holder, int position) {
            if (holder.itemView instanceof TextView) {
                TextView textView = (TextView) holder.itemView;
                String itemData = data.get(position);
                textView.setText(itemData);
            }
            //五颜六色的背景，容易被识别
            int type = getItemViewType(position);
            ViewType itemViewType = ViewType.LINEAR_LAYOUT;
            for (ViewType viewType : ViewType.values()) {
                if (viewType.type == type) {
                    itemViewType = viewType;
                    break;
                }
            }
            int[] colors = null;
            switch (itemViewType) {
                case LINEAR_LAYOUT:
                    colors = linearLayoutColors;
                    break;
                case GRID_LAYOUT:
                    colors = gridLayoutColors;
                    break;
                case STAGGERED_GRID_LAYOUT_SMALL:
                    colors = new int[]{staggeredGridLayoutColors[0]};
                    break;
                case STAGGERED_GRID_LAYOUT_BIG:
                    colors = new int[]{staggeredGridLayoutColors[1]};
                    break;
                default:
                    break;
            }
            int color = colors[position % colors.length];
            holder.itemView.setBackgroundColor(color);
        }

        @Override
        public int getItemViewType(int position) {
            if (position < 5) {
                return ViewType.LINEAR_LAYOUT.type;
            } else if (position < 9) {
                return ViewType.GRID_LAYOUT.type;
            } else if (position < 16) {
                return position % 2 == 0 ? ViewType.STAGGERED_GRID_LAYOUT_SMALL.type : ViewType.STAGGERED_GRID_LAYOUT_BIG.type;
            } else {
                return ViewType.LINEAR_LAYOUT.type;
            }
        }

        @Override
        public int getItemCount() {
            return data.size();
        }
    }

    enum ViewType {
        /**
         *
         */
//        LINEAR_LAYOUT(1, VictorApplication.INSTANCE.getResources().getDimensionPixelSize(R.dimen.dim57)),
        LINEAR_LAYOUT(1, ViewGroup.LayoutParams.WRAP_CONTENT),
        /**
         *
         */
        GRID_LAYOUT(2, VictorApplication.INSTANCE.getResources().getDimensionPixelSize(R.dimen.dp_180)),
        /**
         *
         */
        STAGGERED_GRID_LAYOUT_SMALL(3, VictorApplication.INSTANCE.getResources().getDimensionPixelSize(R.dimen.dp_220)),
        /**
         *
         */
        STAGGERED_GRID_LAYOUT_BIG(4, VictorApplication.INSTANCE.getResources().getDimensionPixelSize(R.dimen.dp_294));

        private final int type;
        private final int height;

        ViewType(int type, int height) {
            this.type = type;
            this.height = height;
        }
    }

    private final class ShoppingViewHolder extends RecyclerView.ViewHolder {

        ShoppingViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }
}
